<?php

namespace app\controller;

use app\traits\ControllerTrait;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use app\lib\WxBizDataCrypt;
use app\constants\Wx;
use think\Exception;

/**
 * Class AdminUser
 * @package app\controller
 */
class AdminUser extends ControllerTrait
{
    public function index()
    {
        //
    }

    /** 账号密码登录 校验 */
    public function login()
    {
        $param = $this->request->param();
        $rule = [
            "account|用户名" => "require",
            "password|密码" => "require"
        ];
        $this->validate($param, $rule);
        $user = app('adminUserModel')
            ->field(["uid", "avatar", "account", "mark", "phone", 'openid', 'gender', 'nickName'])
            ->where([
                'account' => $param['account'],
                'password' => $param['password'],
                'status' => 0,
            ])->find();
        if (!empty($user)) {
            $msg = '登录校验成功';
            $data = array(
                'info' => $user,
                'token' => app("jwt")->signToken($user["id"])
            );
            $this->success($data, $msg);
        } else {
            $msg = '登陆失败,账号或密码错误';
            $this->error(1, $msg);
        }
    }

    /** 微信登录 code2Session 校验 */
    public function code2Session()
    {
        $param = $this->request->param();
        $rule = ["code|code" => "require"];
        $this->validate($param, $rule);
        //微信公众平台获取access token url
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        //获取access token时需要携带的参数
        $params = array(
            'appid' => Wx::$appid,
            'secret' => Wx::$secret,
            'js_code' => $param['code'],
            'grant_type' => 'authorization_code'
        );
        $resp = null;
        try {
            //使用GuzzleHTTP发送get请求
            $client = new Client();
            $resp = $client->request('GET', $url . http_build_query($params));
        } catch (GuzzleException $e) {
            echo $e;
        }
        if (empty($resp)) {
            $this->error(1, '微信 code2Session 验证失败');
        }
        //获取微信公众平台的response
        $res = json_decode($resp->getBody(), true);
        $user = app('adminUserModel')
            ::where(['status' => 0, 'openid' => $res['openid']])
            ->findOrEmpty();
        $uid = create_guid();
        if ($user->isEmpty()) {
            $user->save(['openid' => $res['openid'], 'session_key' => $res['session_key'], 'uid' => $uid]);
        } else {
            $user->session_key = $res['session_key'];
            $user->save();
        }

        if ($user['mark'] === '微信用户' && $user['is_login'] === 1) {
            $resData = array(
                'info' => app("adminUserModel")
                    ->field(["uid", "avatar", "account", "mark", "phone", 'openid', 'gender', 'nickName'])
                    ->where('openid', $res["openid"])
                    ->find(),
                'token' => app("jwt")->signToken($res["openid"])
            );
            $this->success($resData, '微信登录校验成功');
        } else {
            $resData = array(
//                'uid' => $uid,
                'openid' => $res['openid'],
                'token' => app("jwt")->signToken($res["openid"])
            );
            $this->success($resData, '微信登录校验成功');
        }
    }


    /** 解密用户信息 */
    public function decryptionWX()
    {
        $param = $this->request->param();
        $rule = [
            "openid|openid" => "require",
            "encryptedData|用户信息的加密数据" => "require",
            "iv|加密算法的初始向量" => "require",
        ];
        $this->validate($param, $rule);

        $User = app("adminUserModel")->where(['openid' => $param['openid']])->find();
        $sessionKey = $User['session_key'];
        $encryptedData = $param['encryptedData'];
        $iv = $param['iv'];

        $pc = new WxBizDataCrypt(Wx::$appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        $data = json_decode($data);
        if ($data) {
            app("adminUserModel")
                ->where(['openid' => $param['openid']])
                ->find()
                ->save([
                    'nickName' => $data->nickName,
                    'avatar' => $data->avatarUrl,
                    'gender' => $data->gender,
                    'password' => '123456',
                    'is_login' => '1',
                    'mark' => "微信用户"
                ]);
        }
        if ($errCode === 0) {
            $user = app("adminUserModel")
                ->field(["uid", "avatar", "account", "mark", "phone", 'openid', 'gender', 'nickName'])
                ->where(['status' => 0, 'openid' => $param['openid']])
                ->find();
            $this->success($user, '解密成功');
        } else {
            $this->error($errCode, '解密失败');
        }
    }

    /** 绑定手机号 */
    public function bindPhone()
    {
        $param = $this->request->param();
        $rule = [
            "openid|openid" => "require",
            "phone|手机号码" => "require|mobile",
        ];
        $this->validate($param, $rule);
    }

    /** 用户登出方法 */
    public function logOut()
    {
        $param = $this->request->param();
        $rule = [
            "uid|用户 id" => "require",
        ];
        $this->validate($param, $rule);
        app('adminUserModel')
            ::where(['status' => 0, 'uid' => $param['uid']])
            ->find()
            ->save(['is_login' => "0"]);
        $this->success('0', '退出登录成功');
    }


    /** 管理员管理用户列表 */
    public function userList()
    {
        //
    }

    /** 登录用户信息 */
    public function userInfo()
    {
        $param = $this->request->param();
        $rule = [
            "uid|用户 id" => "require",
        ];
        $this->validate($param, $rule);
        $user = app("adminUserModel")
            ->field(["uid", "avatar", "account", "mark", "phone", 'openid', 'gender', 'nickName'])
            ->where(['status' => 0, 'uid' => $param['uid']])
            ->find();

        $data = array(
            'userInfo' => $user
        );
        $this->success($data, '登录用户基本信息');
    }

    /** 超级管理员添加登录用户 */
    public function addUser()
    {
        $param = $this->request->param();
        $rule = [
            "account|用户名" => "require",
            "phone|手机号码" => "require|mobile",
        ];
        $this->validate($param, $rule);
        $user = app("adminUserModel")->find($this->uid);
        //验证超级管理员

        if ($user->authority === 2) {
            $addUser = app("adminUserModel")->where(['account' => $param['account']])->find();
            if (empty($addUser)) {
                $addUser = app("adminUserModel");
            }
            $addUser->save([
                'account' => $param['account'],
                'phone' => $param['phone'],
                'password' => '123456',
                'mark' => ($param['mark']) ? ($param['mark']) : 0,
                'authority' => (empty($param['authority']) && $param['authority'] < 2) ? ($param['authority']) : "0",
            ]);
            $this->success(['msg' => '操作成功']);
        } else {
            $this->success(['msg' => '操作失败，非管理员身份']);
        }
    }

}
